package com.example.ruralservicedigitalplatform.controller.villager;

import com.example.ruralservicedigitalplatform.comment.Result;
import com.example.ruralservicedigitalplatform.constant.JwtClaimsConstant;
import com.example.ruralservicedigitalplatform.domain.dto.VillagerDto;
import com.example.ruralservicedigitalplatform.domain.dto.VillagerEditDto;
import com.example.ruralservicedigitalplatform.domain.dto.VillagerLoginDto;
import com.example.ruralservicedigitalplatform.domain.po.Villager;
import com.example.ruralservicedigitalplatform.domain.vo.VillagerLoginVO;
import com.example.ruralservicedigitalplatform.properties.JwtProperties;
import com.example.ruralservicedigitalplatform.service.VillagerService;
import com.example.ruralservicedigitalplatform.utils.JwtUtil;
import com.example.ruralservicedigitalplatform.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/villager/villager")
@Tag(name = "村民列表")
public class VillagerController {
    @Autowired
    private VillagerService villagerService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    @Operation(summary = "微信登录")
    public Result<VillagerLoginVO> login(@RequestBody VillagerLoginDto villagerLoginDto){
        log.info("微信用户登录：{}",villagerLoginDto.getCode());
        //微信登录
        Villager villager = villagerService.wxLogin(villagerLoginDto);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.VILLAGER_ID,villager.getVillagerId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        VillagerLoginVO villagerLoginVO = VillagerLoginVO.builder()
                .villagerId(villager.getVillagerId())
                .openid(villager.getOpenid())
                .token(token)
                .build();

        return Result.success(villagerLoginVO);
    }


}